package com.lhy.admin.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lhy.admin.mapper.UserRoleMapper;
import com.lhy.admin.model.User;
import com.lhy.admin.model.UserRole;
import com.lhy.admin.util.CollectionUtil;
import com.lhy.admin.common.mvcplus.service.SimpleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserRoleService extends SimpleService<UserRoleMapper, UserRole> {

    @Autowired
    UserService userService;


    public boolean deleteUserRole(String name, Set<Long> roleIds) {
        return this.remove(getNameRoleIdExample(name, roleIds));
    }

    public boolean deleteUserRole(Long userId, Set<Long> roleIds) {
        return this.remove(Wrappers.lambdaQuery(UserRole.class).eq(UserRole::getUserId, userId).in(UserRole::getRoleId, roleIds));
    }

    public boolean addUserRole(Long userId, Set<Long> roleIds) {
        roleIds.forEach(t-> this.save(new UserRole().setUserId(userId).setRoleId(t)));
        return true;
    }

    private Wrapper<UserRole> getNameRoleIdExample(String name, Set<Long> roleIds) {
        User cond = userService.getOne(new User().setName(name)).orElseThrow(() -> new RuntimeException("用戶不存在"));
        return Wrappers.lambdaQuery(UserRole.class).eq(UserRole::getUserId, cond.getId()).in(UserRole::getRoleId, roleIds);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateUserRole(String name, List<Long> newRoleIds) {
        User user = userService.getOne(new User().setName(name)).orElseThrow(() -> new RuntimeException("用戶不存在"));
        long userId = new BigDecimal(user.getId()).longValue();
        log.debug("将更新角色的用户：{},{}", name, userId);
        log.debug("新roleIds:{}", CollectionUtil.toString(newRoleIds));

        //查询原有roles
        List<UserRole> oldUserRoles = this.list(new UserRole().setUserId(userId));
        List<Long> oldUserRoleIds = oldUserRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        log.debug("已存在的roleIds:{}", CollectionUtil.toString(oldUserRoleIds));

        //需删除的userRoleIds
        List<Long> deletedUserRoleIds = oldUserRoles.stream()
                .filter(item -> !newRoleIds.contains(item.getRoleId()))
                .map(UserRole::getId)
                .collect(Collectors.toList());
        log.debug("需要删除的roleIds:{}", CollectionUtil.toString(deletedUserRoleIds));
        if (!deletedUserRoleIds.isEmpty()) {
            this.remove(Wrappers.lambdaQuery(UserRole.class).in(UserRole::getId,deletedUserRoleIds));
        }

        //需要新增的
        List<UserRole> addUserRoleIds = newRoleIds.stream()
                .filter(item -> !oldUserRoleIds.contains(item))
                .map(aLong -> new UserRole().setRoleId(aLong).setUserId(userId))
                .collect(Collectors.toList());
        log.debug("需要新增的roleIds:{}", CollectionUtil.toString(addUserRoleIds));
        addUserRoleIds.forEach(this::save);

    }
}
